<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据监控 - 智能工业数据采集与分析系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }
        .sidebar {
            background-color: #2c3e50;
            color: white;
            min-height: 100vh;
            position: fixed;
        }
        .sidebar a {
            color: #ecf0f1;
            display: block;
            padding: 12px 15px;
            text-decoration: none;
            transition: background-color 0.3s;
        }
        .sidebar a:hover {
            background-color: #34495e;
        }
        .sidebar a.active {
            background-color: #16a085;
        }
        .content {
            margin-left: 250px;
            padding: 20px;
        }
        .card {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s, box-shadow 0.3s;
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .status-green {
            background-color: #27ae60;
        }
        .status-yellow {
            background-color: #f39c12;
        }
        .status-red {
            background-color: #e74c3c;
        }
        .chart-container {
            position: relative;
            height: 300px;
            width: 100%;
            margin-bottom: 20px;
        }
        .parameter-card {
            padding: 15px;
            border-radius: 8px;
            background-color: white;
            margin-bottom: 15px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .parameter-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .parameter-name {
            font-weight: bold;
            color: #2c3e50;
        }
        .parameter-value {
            font-size: 28px;
            font-weight: bold;
            color: #3498db;
        }
        .parameter-unit {
            font-size: 18px;
            color: #95a5a6;
            margin-left: 5px;
        }
        .threshold-line {
            position: absolute;
            width: 100%;
            height: 2px;
            background-color: #e74c3c;
            z-index: 10;
            pointer-events: none;
        }
        .range-selector {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 15px;
        }
        .range-btn {
            padding: 5px 15px;
            margin-left: 5px;
            background-color: #ecf0f1;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .range-btn.active {
            background-color: #3498db;
            color: white;
        }
    </style>
</head>
<body>
    <div class="sidebar" style="width: 250px;">
        <div class="sidebar-header p-4 text-center">
            <h4><i class="fa fa-industry"></i> 工业数据系统</h4>
        </div>
        <div class="sidebar-menu">
            <a href="/" class=""><i class="fa fa-dashboard mr-2"></i> 仪表盘</a>
            <a href="/dashboard" class="active"><i class="fa fa-bar-chart mr-2"></i> 数据监控</a>
            <a href="/alarms"><i class="fa fa-bell mr-2"></i> 报警中心</a>
            <a href="/maintenance"><i class="fa fa-wrench mr-2"></i> 维护管理</a>
            <a href="/reports"><i class="fa fa-file-text mr-2"></i> 报表生成</a>
        </div>
    </div>

    <div class="content">
        <div class="container-fluid">
            <div class="row mb-4">
                <div class="col-12">
                    <div class="d-flex justify-content-between align-items-center">
                        <h2>数据监控中心</h2>
                        <div class="d-flex align-items-center">
                            <span id="connection-status" class="mr-4">
                                <span class="status-indicator status-green"></span>
                                <span>系统正常</span>
                            </span>
                            <span id="current-time">--:--:--</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 时间范围选择器 -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="range-selector">
                        <button class="range-btn active" data-range="1">1小时</button>
                        <button class="range-btn" data-range="6">6小时</button>
                        <button class="range-btn" data-range="12">12小时</button>
                        <button class="range-btn" data-range="24">24小时</button>
                        <button class="range-btn" data-range="72">3天</button>
                        <button class="range-btn" data-range="168">7天</button>
                    </div>
                </div>
            </div>

            <!-- 实时数据卡片 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="parameter-card">
                        <div class="parameter-header">
                            <span class="parameter-name">温度1</span>
                            <span class="status-indicator status-green"></span>
                        </div>
                        <div class="d-flex items-baseline">
                            <span id="temp1-value" class="parameter-value">45.0</span>
                            <span class="parameter-unit">℃</span>
                        </div>
                        <div class="text-xs text-gray-500 mt-2">最后更新: <span id="temp1-update">--:--:--</span></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="parameter-card">
                        <div class="parameter-header">
                            <span class="parameter-name">温度2</span>
                            <span class="status-indicator status-green"></span>
                        </div>
                        <div class="d-flex items-baseline">
                            <span id="temp2-value" class="parameter-value">43.0</span>
                            <span class="parameter-unit">℃</span>
                        </div>
                        <div class="text-xs text-gray-500 mt-2">最后更新: <span id="temp2-update">--:--:--</span></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="parameter-card">
                        <div class="parameter-header">
                            <span class="parameter-name">DS18B20温度</span>
                            <span class="status-indicator status-green"></span>
                        </div>
                        <div class="d-flex items-baseline">
                            <span id="ds18b20-value" class="parameter-value">42.5</span>
                            <span class="parameter-unit">℃</span>
                        </div>
                        <div class="text-xs text-gray-500 mt-2">最后更新: <span id="ds18b20-update">--:--:--</span></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="parameter-card">
                        <div class="parameter-header">
                            <span class="parameter-name">维护需求</span>
                            <span class="status-indicator status-green"></span>
                        </div>
                        <div class="d-flex items-baseline">
                            <span id="maintenance-score" class="parameter-value">10.0</span>
                            <span class="parameter-unit">%</span>
                        </div>
                        <div class="text-xs text-gray-500 mt-2">维护等级: <span id="maintenance-level">低</span></div>
                    </div>
                </div>
            </div>

            <!-- 图表区域 -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">温度趋势</h5>
                            <div class="chart-container">
                                <canvas id="temperatureChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">压力趋势</h5>
                            <div class="chart-container">
                                <canvas id="pressureChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">振动趋势</h5>
                            <div class="chart-container">
                                <canvas id="vibrationChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">传感器数据分布</h5>
                            <div class="chart-container">
                                <canvas id="distributionChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 更新当前时间
        function updateCurrentTime() {
            const now = new Date();
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            document.getElementById('current-time').textContent = `${hours}:${minutes}:${seconds}`;
        }
        setInterval(updateCurrentTime, 1000);
        updateCurrentTime();

        // 图表对象
        let temperatureChart, pressureChart, vibrationChart, distributionChart;
        let currentRange = 1; // 默认1小时

        // 初始化温度趋势图
        function initTemperatureChart() {
            const ctx = document.getElementById('temperatureChart').getContext('2d');
            
            // 生成模拟数据
            const data = generateChartData(currentRange);
            
            temperatureChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [
                        {
                            label: '温度传感器1 (℃)',
                            data: data.temp1Data,
                            borderColor: '#3498db',
                            backgroundColor: 'rgba(52, 152, 219, 0.1)',
                            tension: 0.4,
                            fill: false
                        },
                        {
                            label: '温度传感器2 (℃)',
                            data: data.temp2Data,
                            borderColor: '#e74c3c',
                            backgroundColor: 'rgba(231, 76, 60, 0.1)',
                            tension: 0.4,
                            fill: false
                        },
                        {
                            label: 'DS18B20温度 (℃)',
                            data: data.ds18b20Data,
                            borderColor: '#2ecc71',
                            backgroundColor: 'rgba(46, 204, 113, 0.1)',
                            tension: 0.4,
                            fill: false
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: false,
                            min: 35,
                            max: 50
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    }
                }
            });
        }

        // 初始化压力趋势图
        function initPressureChart() {
            const ctx = document.getElementById('pressureChart').getContext('2d');
            
            // 生成模拟数据
            const data = generateChartData(currentRange);
            
            pressureChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [
                        {
                            label: '压力传感器1 (bar)',
                            data: data.pressure1Data,
                            borderColor: '#9b59b6',
                            backgroundColor: 'rgba(155, 89, 182, 0.1)',
                            tension: 0.4,
                            fill: false
                        },
                        {
                            label: '压力传感器2 (bar)',
                            data: data.pressure2Data,
                            borderColor: '#e67e22',
                            backgroundColor: 'rgba(230, 126, 34, 0.1)',
                            tension: 0.4,
                            fill: false
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            min: 0,
                            max: 12
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    }
                }
            });
        }

        // 初始化振动趋势图
        function initVibrationChart() {
            const ctx = document.getElementById('vibrationChart').getContext('2d');
            
            // 生成模拟数据
            const data = generateChartData(currentRange);
            
            vibrationChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [
                        {
                            label: '振动传感器1 (V)',
                            data: data.vibration1Data,
                            borderColor: '#1abc9c',
                            backgroundColor: 'rgba(26, 188, 156, 0.1)',
                            tension: 0.4,
                            fill: false
                        },
                        {
                            label: '振动传感器2 (V)',
                            data: data.vibration2Data,
                            borderColor: '#f1c40f',
                            backgroundColor: 'rgba(241, 196, 15, 0.1)',
                            tension: 0.4,
                            fill: false
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            min: 0,
                            max: 5
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    }
                }
            });
        }

        // 初始化传感器数据分布图
        function initDistributionChart() {
            const ctx = document.getElementById('distributionChart').getContext('2d');
            
            // 模拟数据分布
            const data = {
                labels: ['温度', '压力', '振动'],
                datasets: [
                    {
                        label: '正常范围',
                        data: [85, 90, 75],
                        backgroundColor: 'rgba(46, 204, 113, 0.7)',
                        borderColor: 'rgba(46, 204, 113, 1)',
                        borderWidth: 1
                    },
                    {
                        label: '警告范围',
                        data: [10, 8, 15],
                        backgroundColor: 'rgba(243, 156, 18, 0.7)',
                        borderColor: 'rgba(243, 156, 18, 1)',
                        borderWidth: 1
                    },
                    {
                        label: '异常范围',
                        data: [5, 2, 10],
                        backgroundColor: 'rgba(231, 76, 60, 0.7)',
                        borderColor: 'rgba(231, 76, 60, 1)',
                        borderWidth: 1
                    }
                ]
            };
            
            distributionChart = new Chart(ctx, {
                type: 'bar',
                data: data,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                        }
                    },
                    scales: {
                        x: {
                            stacked: true,
                        },
                        y: {
                            stacked: true,
                            beginAtZero: true,
                            max: 100,
                            ticks: {
                                callback: function(value) {
                                    return value + '%';
                                }
                            }
                        }
                    }
                }
            });
        }

        // 生成图表数据
        function generateChartData(hours) {
            // 根据选择的时间范围生成数据点
            const pointCount = hours <= 12 ? hours * 6 : hours * 3; // 1小时到12小时每10分钟一个点，超过12小时每20分钟一个点
            
            const labels = [];
            const temp1Data = [];
            const temp2Data = [];
            const ds18b20Data = [];
            const pressure1Data = [];
            const pressure2Data = [];
            const vibration1Data = [];
            const vibration2Data = [];
            
            const now = new Date();
            const intervalMinutes = hours <= 12 ? 10 : 20;
            
            for (let i = pointCount - 1; i >= 0; i--) {
                const time = new Date(now - i * intervalMinutes * 60000);
                
                // 格式化时间标签
                let timeLabel;
                if (hours <= 12) {
                    timeLabel = `${time.getHours()}:${String(time.getMinutes()).padStart(2, '0')}`;
                } else {
                    timeLabel = `${time.getMonth() + 1}/${time.getDate()} ${time.getHours()}:00`;
                }
                labels.push(timeLabel);
                
                // 生成模拟数据，添加随机波动
                temp1Data.push(45 + Math.random() * 3 - 1.5); // 45±1.5
                temp2Data.push(43 + Math.random() * 2.5 - 1.25); // 43±1.25
                ds18b20Data.push(42.5 + Math.random() * 2 - 1); // 42.5±1
                pressure1Data.push(5.0 + Math.random() * 1 - 0.5); // 5±0.5
                pressure2Data.push(4.8 + Math.random() * 0.8 - 0.4); // 4.8±0.4
                vibration1Data.push(1.5 + Math.random() * 0.5 - 0.25); // 1.5±0.25
                vibration2Data.push(1.3 + Math.random() * 0.4 - 0.2); // 1.3±0.2
            }
            
            return {
                labels: labels,
                temp1Data: temp1Data,
                temp2Data: temp2Data,
                ds18b20Data: ds18b20Data,
                pressure1Data: pressure1Data,
                pressure2Data: pressure2Data,
                vibration1Data: vibration1Data,
                vibration2Data: vibration2Data
            };
        }

        // 更新图表数据
        function updateCharts() {
            // 销毁现有图表
            if (temperatureChart) temperatureChart.destroy();
            if (pressureChart) pressureChart.destroy();
            if (vibrationChart) vibrationChart.destroy();
            
            // 初始化新图表
            initTemperatureChart();
            initPressureChart();
            initVibrationChart();
        }

        // 更新系统状态
        function updateSystemStatus() {
            fetch('/api/get_status')
                .then(response => response.json())
                .then(data => {
                    // 更新传感器数据
                    document.getElementById('temp1-value').textContent = data.sensors.temperature1.toFixed(1);
                    document.getElementById('temp2-value').textContent = data.sensors.temperature2.toFixed(1);
                    document.getElementById('ds18b20-value').textContent = data.sensors.ds18b20_temp.toFixed(1);
                    
                    // 更新连接状态
                    const connectionStatus = document.getElementById('connection-status');
                    if (data.connected) {
                        connectionStatus.innerHTML = '<span class="status-indicator status-green"></span><span>系统正常</span>';
                    } else {
                        connectionStatus.innerHTML = '<span class="status-indicator status-red"></span><span>连接断开</span>';
                    }
                    
                    // 更新最后更新时间
                    const lastUpdate = new Date(data.last_update * 1000);
                    const hours = String(lastUpdate.getHours()).padStart(2, '0');
                    const minutes = String(lastUpdate.getMinutes()).padStart(2, '0');
                    const seconds = String(lastUpdate.getSeconds()).padStart(2, '0');
                    const updateTime = `${hours}:${minutes}:${seconds}`;
                    
                    document.getElementById('temp1-update').textContent = updateTime;
                    document.getElementById('temp2-update').textContent = updateTime;
                    document.getElementById('ds18b20-update').textContent = updateTime;
                })
                .catch(error => {
                    console.error('获取系统状态失败:', error);
                });
        }

        // 更新维护信息
        function updateMaintenanceInfo() {
            // 模拟维护数据
            const maintenanceScore = Math.floor(Math.random() * 30) + 5; // 5-35%之间的随机数
            let maintenanceLevel = '低';
            let statusColor = 'status-green';
            
            if (maintenanceScore > 70) {
                maintenanceLevel = '高';
                statusColor = 'status-red';
            } else if (maintenanceScore > 30) {
                maintenanceLevel = '中';
                statusColor = 'status-yellow';
            }
            
            // 更新UI
            document.getElementById('maintenance-score').textContent = maintenanceScore.toFixed(1);
            document.getElementById('maintenance-level').textContent = maintenanceLevel;
            
            // 更新状态指示器
            const statusIndicator = document.querySelector('.parameter-card:last-child .status-indicator');
            statusIndicator.className = `status-indicator ${statusColor}`;
        }

        // 事件监听器：时间范围选择
        document.querySelectorAll('.range-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                // 移除所有按钮的active类
                document.querySelectorAll('.range-btn').forEach(b => b.classList.remove('active'));
                // 添加当前按钮的active类
                this.classList.add('active');
                // 更新当前时间范围
                currentRange = parseInt(this.getAttribute('data-range'));
                // 更新图表
                updateCharts();
            });
        });

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化图表
            initTemperatureChart();
            initPressureChart();
            initVibrationChart();
            initDistributionChart();
            
            // 初始化系统状态
            updateSystemStatus();
            
            // 初始化维护信息
            updateMaintenanceInfo();
            
            // 定期更新系统状态
            setInterval(updateSystemStatus, 5000);
            
            // 定期更新维护信息
            setInterval(updateMaintenanceInfo, 30000);
        });
    </script>
</body>
</html>